package com.hy.trie;

/**
 * Created With IntelliJ IDEA.
 * Descriptions:
 * author: Mr.Du
 * Date: 2023/10/12
 * Time: 15:35
 */
class Trie {
    Trie[] child = new Trie[26];;
    boolean isEndTrie = false;
    public Trie(){
    }

    public void insert(String word) {
        Trie p = this;
        for(int i = 0;i < word.length();i++){
            char c = word.charAt(i);
            int index = c - 'a';
            if(p.child[index] == null){
                p.child[index] = new Trie();
            }
            p = p.child[index];
        }
        p.isEndTrie = true;
    }

    public boolean search(String word) {
        Trie p = this;
        for(int i = 0;i < word.length();i++){
            char c = word.charAt(i);
            int index = c - 'a';
            if(p.child[index] == null){
                return false;
            }
            p = p.child[index];

        }
        return p != null && p.isEndTrie;
    }

    public boolean startsWith(String prefix) {
        Trie p = this;
        for(int i = 0;i < prefix.length();i++){
            if(p == null) return false;
            char c = prefix.charAt(i);
            int index = c - 'a';
            if(p.child[index] == null){
                return false;
            }
            p = p.child[index];

        }
        return true;
    }
}

